package com.sdcx.agrobank.util;

import com.sdcx.agrobank.net.HttpRetrofitUtil;

import java.io.IOException;

import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

public class AppInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        int maxAge = 60 * 60; // 有网络时 设置缓存超时时间1个小时
        int maxStale = 60 * 60 * 24 * 28; // 无网络时，设置超时为4周

        Request request = chain.request();
        Request.Builder builder = request.newBuilder();
        //有网
        if (HttpRetrofitUtil.get().isnetwork(App.getAppContext())){
            builder.cacheControl(CacheControl.FORCE_NETWORK);
        } else {
            builder.cacheControl(CacheControl.FORCE_CACHE);
        }
     //   String string = SPUtils.getInstance().getString("userId");
        builder.addHeader("ak", "0110010010000");
        builder.addHeader("Content-Type", "application/x-www-form-urlencoded");
      /*  if (string.isEmpty()){

        } else {
            builder.addHeader("userId", SPUtils.getInstance().getString("userId"));
            builder.addHeader("sessionId", SPUtils.getInstance().getString("sessionId"));
        }*/

        Request build = builder.build();
        Response proceed = chain.proceed(build);
        if (HttpRetrofitUtil.get().isnetwork(App.getAppContext())){
            //设置缓存多长时间是可用的
            proceed = proceed.newBuilder()
                    //之所以移除Pragma,是因为服务器不支持,Pragma的字段会干扰我们的缓存
                    .removeHeader("Pragma")
                    .header("Cache-Control", "public, max-age=" + maxAge)
                    .build();
        } else {
            //设置过期maxStale多长时间之后依然可用
            proceed = proceed.newBuilder()
                    .removeHeader("Pragma")
                    .header("Cache-Control", "public, only-if-cached, max-stale="
                            + maxStale)
                    .build();
        }
        return proceed;
    }
}
